from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response

from goods.models import SKU, GoodsCategory, SPU
from meiduo_admin.serializers.skus import SKUSerializer, GoodsCategorySerializer, SPUSpecificationSerializer
from meiduo_admin.utils import PageNum


class SKUView(ModelViewSet):
    # 序列化器
    serializer_class = SKUSerializer

    # 查询集
    queryset = SKU.objects.all()

    # 分页器
    pagination_class = PageNum

    # 权限
    permission_classes = [IsAdminUser]

    # 根据keyword 重写获取查询集数据的方法
    def get_queryset(self):
        if self.request.query_params.get('keyword') == '':
            return SKU.objects.all()

        # 修改时，获取单一字段数据，没有keyword
        elif self.request.query_params.get('keyword') is None:
            return SKU.objects.all()

        else:
            return SKU.objects.filter(name__contains=self.request.query_params.get('keyword'))

    @action(methods=['get'], detail=False)  # 不需要pk值（获取所有，detail=False）
    def categories(self, request):
        """
        获取三级分类数据
        :param request:
        :return:
        """
        data = GoodsCategory.objects.filter(subs__id=None)

        ser = GoodsCategorySerializer(data=data, many=True)
        ser.is_valid()

        return Response(ser.data)

    def specs(self, request, pk):
        """
        获取spu商品规格信息
        :param request:
        :param pk:
        :return:
        """
        # 1 查询spu对象
        spu = SPU.objects.get(id=pk)
        # 2 关联查询spu所关联的规格表
        data=spu.specs.all()
        # 3 序列化返回规格信息
        ser = SPUSpecificationSerializer(data=data, many=True)  # 如果这行写data=data， 下一行必须验证，不写不用验证
        ser.is_valid()

        return Response(ser.data)